import ButtonManager from './ButtonManager.js'; // 导入按钮管理模块

const ClearStock = {
  buttonId: 'clearStock', // 按钮 ID
  defaultText: '3. 下架商品清零库存', // 默认按钮文本

  // 初始化函数
  init() {
    document.getElementById(this.buttonId).addEventListener('click', this.handleClick.bind(this)); // 绑定点击事件
  },

  // 点击事件处理函数
  async handleClick() {
    ButtonManager.updateButtonState(this.buttonId, '3. 下架商品清零库存-处理中...', true); // 更新按钮状态为加载中
    ButtonManager.disableAllButtons(this.buttonId); // 禁用其他按钮

    try {
      const warehouseId = warehouseIdInput.value.trim();
      if (warehouseId) {
        console.log("输入的仓库ID:", warehouseId);
        // 这里可以添加更多的逻辑，比如将仓库ID存储到 localStorage 或者发送到后台脚本
      }else {
        console.log('请输入仓库id')
        alert('请输入仓库id');
        return
      }
      const { mallId, antiContent } = await new Promise((resolve) => {
        chrome.storage.local.get(['mallId', 'antiContent'], resolve); // 从本地存储获取 mallId 和 antiContent
      });

      if (!mallId || !antiContent) {
        console.error("mallId 或 antiContent 未找到"); // 检查是否获取到必要参数
        return;
      }

      const [tab] = await chrome.tabs.query({ active: true, currentWindow: true }); // 获取当前标签页

      const results = await chrome.scripting.executeScript({
        target: { tabId: tab.id }, // 注入脚本到当前标签页
        func: executeClearStock, // 执行清零库存逻辑
        args: [mallId, antiContent,warehouseId], // 传递参数
      });

      if (results && results[0] && results[0].result) {
        console.log("下架商品清零库存完成，返回数据:", results[0].result); // 输出清零库存结果
      } else {
        console.error("未获取到有效数据"); // 输出错误信息
      }
    } catch (error) {
      console.error("下架商品清零库存失败:", error); // 捕获错误
    } finally {
      ButtonManager.resetButtonState(this.buttonId, this.defaultText); // 恢复按钮状态
      ButtonManager.enableAllButtons(); // 启用所有按钮
    }
  },
};

// 清零库存逻辑函数
function executeClearStock(j_mallid, j_anti_content,j_warehouseId = '') {
  return new Promise((resolve, reject) => {
    console.log("开始执行下架商品清零库存逻辑...");
    console.log("接收到的参数:", { j_mallid, j_anti_content });
    
    let j_total = 1;
    let j_pageNum = 1;
    let j_pages = 1;
    let j_pageSize = 100;
    let j_body = { "page": 1, "pageSize": j_pageSize, "skcTopStatus": 200, "skcSecondaryStatus": 1 };
    let j_time = Math.floor(Math.random() * 2) * 1000 + 1000;
    let j_totalZeroNum = 0;
    // let j_warehouseId = "WH-07105905346710196"
    function j_pageQuery() {
      j_body.page = j_pageNum;
      if (j_pageNum > j_pages) {
        console.log('完成操作：处理清零库存');
        resolve('完成操作：处理清零库存');
        return;
      }

      fetch("https://seller.kuajingmaihuo.com/bg-visage-mms/product/skc/pageQuery", {
        method: 'POST',
        headers: {
          accept: '*/*',
          'accept-language': 'zh-CN,zh;q=0.9',
          'anti-content': j_anti_content,
          'cache-control': 'max-age=0',
          'content-type': 'application/json',
          mallid: j_mallid,
          priority: 'u=1, i',
          'sec-ch-ua': '"Not(A:Brand";v="99", "Google Chrome";v="133", "Chromium";v="133"',
          'sec-ch-ua-mobile': '?0',
          'sec-ch-ua-platform': '"macOS"',
          'sec-fetch-dest': 'empty',
          'sec-fetch-mode': 'cors',
          'sec-fetch-site': 'same-origin'
        },
        referrer: 'https://seller.kuajingmaihuo.com/goods/product/list?isSemiManagedSupplier=1&productId=613595268',
        referrerPolicy: 'strict-origin-when-cross-origin',
        body: JSON.stringify(j_body),
        mode: 'cors',
        credentials: 'include'
      })
        .then(response => {
          if (!response.ok) {
            throw new Error('Network response was not ok');
          }
          return response.json();
        })
        .then(data => {
          if (data.success) {
            if (j_pageNum === 1) {
              j_total = data.result.total;
              j_pages = Math.ceil(j_total / j_pageSize);
            }
            j_pageNum++;

            let pageItems = data.result.pageItems;
            let arr = [];
            pageItems.forEach((item, index) => {
              let skuStockChangeList = [];
              item.productSkuSummaries.forEach((itemSub, indexSub) => {
                if (itemSub.virtualStock > 0) {
                  skuStockChangeList.push({
                    productSkuId: itemSub.productSkuId,
                    stockDiff: -itemSub.virtualStock,
                    currentStockAvailable: itemSub.virtualStock,
                    currentShippingMode: 1,
                    warehouseId: j_warehouseId // 仓库ID
                  });
                }
              });

              if (skuStockChangeList.length > 0) {
                arr.push({
                  productId: item.productId,
                  skuStockChangeList: skuStockChangeList,
                  skuTypeChangeList: [],
                  isCheckVersion: true
                });
              }
            });

            if (arr.length > 0) {
              console.log('第' + j_pageNum + '页,可清零', arr);
              setTimeout(function () { j_updateMmsBtgProductSalesStock(arr, 0); }, j_time);
            } else {
              console.log('第' + j_pageNum + '页,没有可清零的商品');
              setTimeout(function () { j_pageQuery(); }, j_time);
            }
          } else {
            console.warn('下架失败，' + data.errorMsg);
          }
        })
        .catch(error => {
          console.error('There was a problem with your fetch operation:', error);
          reject(error);
        });
    }

    let j_errNum = 0;
    function j_updateMmsBtgProductSalesStock(arr, i) {
      let arri = i;
      if (arri >= arr.length) {
        setTimeout(function () { j_pageQuery(); }, j_time);
        console.log('清零库存成功数：', j_totalZeroNum);
        return;
      }

      fetch("https://seller.kuajingmaihuo.com/marvel-mms/cn/api/kiana/starlaod/btg/sales/stock/updateMmsBtgProductSalesStock", {
        method: 'POST',
        headers: {
          accept: '*/*',
          'accept-language': 'zh-CN,zh;q=0.9',
          'anti-content': j_anti_content,
          'cache-control': 'max-age=0',
          'content-type': 'application/json',
          mallid: j_mallid,
          priority: 'u=1, i',
          'sec-ch-ua': '"Not(A:Brand";v="99", "Google Chrome";v="133", "Chromium";v="133"',
          'sec-ch-ua-mobile': '?0',
          'sec-ch-ua-platform': '"macOS"',
          'sec-fetch-dest': 'empty',
          'sec-fetch-mode': 'cors',
          'sec-fetch-site': 'same-origin'
        },
        referrer: 'https://seller.kuajingmaihuo.com/goods/product/list?isSemiManagedSupplier=1&productId=613595268',
        referrerPolicy: 'strict-origin-when-cross-origin',
        body: JSON.stringify(arr[i]),
        mode: 'cors',
        credentials: 'include'
      })
        .then(response => {
          if (!response.ok) {
            throw new Error('Network response was not ok');
          }
          return response.json();
        })
        .then(data => {
          if (data.success) {
            j_totalZeroNum++;
            console.log('清零库存成功');
            arri++;
            setTimeout(function () { j_updateMmsBtgProductSalesStock(arr, arri); }, j_time);
          } else {
            if (j_errNum < 5) {
              setTimeout(function () { j_updateMmsBtgProductSalesStock(arr, arri); }, j_time);
            } else {
              console.log(arr[arri].productId, '清零失败');
              arri++;
              setTimeout(function () { j_updateMmsBtgProductSalesStock(arr, arri); }, j_time);
            }
          }
        })
        .catch(error => {
          console.error('There was a problem with your fetch operation:', error);
          reject(error);
        });
    }

    // 开始执行下架商品清零库存逻辑
    j_pageQuery();
  });
}

export default ClearStock; // 导出模块